const mysql = require('mysql')
const moment = require('moment')
const axios = require('axios')
const { mysqlConfig } = require('./utils/db')

const connection = mysql.createConnection(mysqlConfig)

connection.connect(function(error) {
  if (error) throw error
  console.log('数据库连接成功')
})

const sqlQuery = 'SELECT * FROM require_goods'
connection.query(sqlQuery, [], (error, results, fields) => {
  if (error) throw error
  // 处理查询结果
  dealResults(results.map(item => item.goods_id))
})

const dealResults = async (list) => {
  for (let index = 0; index < list.length; index++) {
    await getGoods_info(list[index])
  }
  connection.end((error) => {
    if (error) throw error
    console.log('数据库连接已关闭')
  })
}

const getGoods_info = (goods_id) => {
  return new Promise((resolve, reject) => {
    axios.get(`https://buff.163.com/api/market/goods/sell_order?game=dota2&goods_id=${goods_id}&page_num=1&sort_by=default&mode=&allow_tradable_cooldown=1&_=${moment().valueOf()}`).then(res => {
      const goods_data = res.data.data

      let goods_name = goods_data.goods_infos[goods_id].name
      let goods_price = res.data.data.items[0].price
      let record_time = moment().format('YYYY-MM-DD HH:mm:ss')

      const insertSql = 'INSERT INTO goods_info (goods_name, goods_id, goods_price, record_time) VALUES (?, ?, ?, ?)'
      const insertValues = [goods_name, goods_id, goods_price, record_time]
      connection.query(insertSql, insertValues, function (error, results, fields) {
        if (error) {
          reject(error)
        } else {
          resolve()
        }
      })
    }).catch(err => {
      reject(err)
    })
    
  })
  
}

